<template>
  <!-- 书写html结构 只可以有一个div 但是可以嵌套多个div -->
  <div>
    <!-- 根据参数查询 和 添加数据 -->
    <el-row>
      <el-col :span="4">
        <el-input
          v-model="searchForm.storeName"
          placeholder="请输入门店名称"></el-input>
      </el-col>
      <el-col :span="4">
        <el-input
          v-model="searchForm.phone"
          placeholder="请输入手机号码"></el-input>
      </el-col>
      <el-col :span="4">
        <el-select v-model="searchForm.status" placeholder="请选门店状态">
          <el-option label="营业中" value="1"></el-option>
          <el-option label="停用" value="0"></el-option>
        </el-select>
      </el-col>
      <el-col :span="6">
        <el-button type="success" icon="el-icon-search" @click="search"
          >搜索</el-button
        >
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd"
          >添加</el-button
        >
      </el-col>
      <el-col :span="6"></el-col>
    </el-row>
    <!-- 查询的数据指定数据 -->
    <el-table :data="tableData" highlight-current-row style="width: 100%">
      <el-table-column sortable width="100" prop="storeName" label="门店名称">
      </el-table-column>
      <el-table-column sortable width="150" prop="address" label="门店地址">
      </el-table-column>
      <el-table-column sortable width="120" prop="phone" label="门店电话">
      </el-table-column>
      <el-table-column sortable width="120" prop="washPrice" label="洗车单价">
      </el-table-column>
      <el-table-column sortable width="100" prop="city" label="所在城市">
      </el-table-column>
      <el-table-column sortable width="100" prop="province" label="所在省份">
      </el-table-column>
      <el-table-column label="门店图片" width="160" height="120">
        <template slot-scope="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.storeimage"></el-image>
        </template>
      </el-table-column>
      <el-table-column sortable width="100" prop="country" label="所在国家">
      </el-table-column>
      <el-table-column sortable width="100" prop="longitude" label="经度">
      </el-table-column>
      <el-table-column sortable width="100" prop="latitude" label="纬度">
      </el-table-column>
      <el-table-column
        sortable
        width="100"
        prop="status"
        :formatter="getStatus3"
        label="门店状态">
      </el-table-column>
      <el-table-column sortable width="100" prop="createBy" label="创建人">
      </el-table-column>
      <el-table-column
        :formatter="formatDate"
        sortable
        width="140"
        prop="createTime"
        label="门店创建时间">
      </el-table-column>
      <el-table-column sortable width="100" prop="updateBy" label="更新人">
      </el-table-column>
      <el-table-column
        :formatter="formatDate"
        sortable
        width="145"
        prop="updateTime"
        label="门店更新时间">
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="250">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button size="mini" type="danger" @click="deleteDept(scope.row)"
            >删除</el-button
          >
          <el-button size="mini" type="success" @click="refresh()"
            >刷新缓存</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页功能 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[3, 6, 12, 24, 120]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

    <!--    添加修改弹窗-->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-form-item
          label="门店名称"
          :label-width="formLabelWidth"
          prop="storeName">
          <el-input v-model="form.storeName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="门店电话"
          :label-width="formLabelWidth"
          prop="phone">
          <el-input v-model="form.washPrice" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="洗车单价"
          :label-width="formLabelWidth"
          prop="phone">
          <el-input v-model="form.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="门店评分"
          :label-width="formLabelWidth"
          prop="country">
          <el-input v-model="form.country" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="门店图片"
          prop="url"
          :label-width="formLabelWidth">
          <!--上传图片  -->
          <el-upload
            style="height: 180px; width: 180px"
            class="avatar-uploader"
            action="http://172.16.9.55:16868/upImage/uploadFile"
            name="file1"
            :show-file-list="false"
            :on-success="handleFileSuccess"
            :before-upload="beforeFileUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <div style="margin-bottom: 15px; margin-left: 60px">
          <span>点击选择门店位置：</span>
          <el-button icon="el-icon-location" circle @click="open"></el-button>
        </div>
        <el-form-item
          label="所在省份"
          :label-width="formLabelWidth"
          :readonly="true"
          prop="province">
          <el-input
            v-model="form.province"
            :disabled="true"
            autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="所在城市"
          :label-width="formLabelWidth"
          prop="city">
          <el-input
            v-model="form.city"
            :disabled="true"
            autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="门店地址"
          :label-width="formLabelWidth"
          prop="address">
          <el-input v-model="form.address" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="经度"
          :label-width="formLabelWidth"
          prop="longitude">
          <el-input
            v-model="form.longitude"
            :disabled="true"
            autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="纬度"
          :label-width="formLabelWidth"
          prop="latitude">
          <el-input
            v-model="form.latitude"
            :disabled="true"
            autocomplete="off"></el-input>
        </el-form-item>
        <el-col :span="2"></el-col>
        <el-form-item
          label="门店状态"
          :label-width="formLabelWidth"
          prop="status">
          <el-select v-model="form.status" placeholder="请选门店状态">
            <el-option label="营业中" value="1"></el-option>
            <el-option label="关闭" value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdate">确 定</el-button>
      </div>
    </el-dialog>

    <!--    地图  -->
    <el-dialog :visible.sync="dialogForm">
      <baidu-map
        style="
          display: flex;
          flex-direction: column-reverse;
          text-align: center;
        "
        id="allmap"
        @ready="mapReady"
        @click="getLocation"
        :scroll-wheel-zoom="true">
        <div style="display: flex; justify-content: center; margin: 15px">
          <bm-auto-complete
            v-model="searchJingwei"
            :sugStyle="{ zIndex: 999999 }">
            <el-input
              v-model="searchJingwei"
              style="width: 300px; margin-right: 15px"
              placeholder="输入详细地址"></el-input>
          </bm-auto-complete>
          <el-button type="primary" @click="getBaiduMapPoint">搜索</el-button>
        </div>
        <bm-map-type
          :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']"
          anchor="BMAP_ANCHOR_TOP_LEFT"></bm-map-type>
        <bm-marker
          v-if="infoWindowShow"
          :position="{ lng: longitude, lat: latitude }">
          <bm-label
            content=""
            :labelStyle="{ color: 'red', fontSize: '24px' }"
            :offset="{ width: -35, height: 30 }" />
        </bm-marker>
        <bm-info-window
          :position="{ lng: longitude, lat: latitude }"
          :show="infoWindowShow">
          <p>经度:{{ this.longitude }}</p>
          <p>纬度:{{ this.latitude }}</p>
          <p>地址:{{ this.AddressDetails }}</p>
        </bm-info-window>
      </baidu-map>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="resetting()">重 置</el-button>
        <el-button type="primary" @click="aaa()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<!--书写组件配置项目  相当于写js代码的地方 -->
<script>
import axios from "axios";
//数据 全是json格式
export default {
  //注册属性 父传子 数据传递
  props: {},
  data() {
    //定义数据
    return {
      //地图开始
      dialogForm: false,
      province: "",
      city: "",
      AddressDetails: "",
      searchJingwei: "",
      infoWindowShow: false,
      longitude: "",
      latitude: "",
      point: "",
      //地图结束

      tableData: [], //表格数据
      currentPage: 1, //页码
      pageSize: 3, //每页显示的数量
      total: 100, //分页总数量
      searchForm: { storeName: "", phone: "", status: "" }, //查询携带的参数
      dialogFormVisible: false, //使弹出不显示
      title: "门店添加", //title 默认为 用户添加
      //添加或者更新数据时 携带的参数
      form: {},
      //弹出框的宽度
      formLabelWidth: "120px",
      openTime: "",
      closeTime: "",
      //角色弹出框设置
      //dialogVisible: false, //角色授权表 取消授权  //不显示角色列表对话框
      //checkAll: false, //是否全选
      //checkedRoles: [], //默认选中的角色
      //roleList: [], //有效角色集合
      //roleIds: "", //定义所有中的所选角色id集合
      isIndeterminate: true,
      tempUserId: 0, //用户id
      //结束
      imageUrl: "", //上传照片设置
    };
  },
  //初始化数据
  created() {
    this.loadData();
    this.getHaveRole(); //查询所有角色的名称
  },

  //方法书写
  methods: {
    //地图初始化
    mapReady({ BMap, map }) {
      // 选择一个经纬度作为中心点
      this.point = new BMap.Point(113.7395, 34.843375);
      map.centerAndZoom(this.point, 12);
      this.BMap = BMap;
      this.map = map;
    },
    //点击获取经纬度
    getLocation(e) {
      this.longitude = e.point.lng;
      this.latitude = e.point.lat;
      this.infoWindowShow = true;
      var _this = this;
      axios
        .get(
          `https://restapi.amap.com/v3/geocode/regeo?location=` +
            this.longitude +
            `,` +
            this.latitude +
            `&key=d1be5f08c6456683633e78f7c28c47df&radius=10&batch=false&roadlevel=1`
        )
        .then(function (response) {
          // 处理成功情况
          console.log(response);
          _this.city = response.data.regeocode.addressComponent.city;
          _this.province = response.data.regeocode.addressComponent.province;
          _this.AddressDetails = response.data.regeocode.formatted_address;
        })
        .catch(function (error) {
          // 处理错误情况
          console.log(error);
        })
        .then(function () {
          // 总是会执行
        });
    },

    open() {
      this.latitude = "";
      this.longitude = "";
      this.AddressDetails = "";
      if (this.title == "门店更新") {
        this.infoWindowShow = true;
        this.latitude = this.form.latitude;
        this.longitude = this.form.latitude;
        this.AddressDetails = this.form.AddressDetails;
      }
      this.dialogForm = true;
    },
    resetting() {
      // alert(JSON.stringify(response));
      this.form.address = '';
      this.form.latitude = '';
      this.form.longitude = '';
      this.form.city = '';
      this.form.province = '';
      this.dialogForm = false;
    },
    aaa() {
      // alert(JSON.stringify(response));
      this.form.address = this.AddressDetails;
      this.form.latitude = this.latitude;
      this.form.longitude = this.longitude;
      this.form.city = this.city;
      this.form.province = this.province;
      this.dialogForm = false;
    },
    getBaiduMapPoint() {
      let that = this;
      let myGeo = new this.BMap.Geocoder();
      myGeo.getPoint(this.searchJingwei, function (point) {
        if (point) {
          that.map.centerAndZoom(point, 15);
          that.latitude = point.lat;
          that.longitude = point.lng;
          that.infoWindowShow = true;
        }
      });
      var _this = this;
      axios
        .get(
          `https://restapi.amap.com/v3/geocode/regeo?location=` +
            this.longitude +
            `,` +
            this.latitude +
            `&key=d1be5f08c6456683633e78f7c28c47df&radius=10&batch=false&roadlevel=1`
        )
        .then(function (response) {
          // 处理成功情况
          console.log(response);
          _this.city = response.data.regeocode.addressComponent.city;
          _this.province = response.data.regeocode.addressComponent.province;
          _this.AddressDetails = response.data.regeocode.formatted_address;
        })
        .catch(function (error) {
          // 处理错误情况
          console.log(error);
        })
        .then(function () {
          // 总是会执行
        });
    },
    //信息窗口关闭
    infoWindowClose() {
      this.latitude = "";
      this.longitude = "";
      // this.AddressDetails = "";
      that.infoWindowShow = false;
    },
    //定义变量_this等于外面的this
    //封装请求数据的方法
    loadData() {
      var _this = this;
      this.$http
        .post("/tbStore/queryPage", {
          pageNo: this.currentPage,
          pageSize: this.pageSize,
          data: this.searchForm,
        })
        .then(function (response) {
          console.log(response);
          //判断是否执行成功
          if (response.data.code == 200) {
            _this.tableData = response.data.data.records;
            _this.total = response.data.data.total;
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },

    //实行每页有多少条的方法
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.loadData();
    },
    //实现跳转页的方法
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.loadData();
    },
    //刷新
    refresh() {
      //原始js重新请求
      location.reload();
    },
    //帐号状态 把状态数字,转换成字符
    getStatus3(row, column, cellValue, index) {
      return cellValue == 1 ? "营业中" : "停用";
    },
    //查询方法
    search() {
      this.loadData();
      //搜索时,使页码为1
      this.currentPage = 1;
    },
    //用户更新的方法
    handleEdit(index, row) {
      var _this = this;
      console.log(index, row);
      //使弹出框显示
      this.dialogFormVisible = true;
      //给用户赋值
      this.title = "门店更新";
      //点击查询携带数据
      this.form = row;
      //照片方法
      this.imageUrl = row.storeimage;
    },
    //添加数据方法
    handleAdd() {
      //使弹出框显示
      this.dialogFormVisible = true;
      //给用户赋值
      this.title = "门店添加";
      //点击查询携带数据
      this.form = {};
      //照片方法
      this.imageUrl = "";
    },
    //关闭方法
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    //删除方法
    deleteDept(row) {
      //确认框提示
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var _this = this;
          this.$http
            .delete("/tbStore/deleteById?id=" + row.storeId)
            .then(function (response) {
              console.log(response);
              if (response.data.code == 200) {
                _this.$message({
                  message: "操作成功",
                  type: "success",
                });
                _this.dialogFormVisible = false;
                _this.loadData();
              } else {
                _this.$message("操作失败");
              }
            })
            .catch(function (error) {
              console.log(error);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //实现门店添加或者更新
    addOrUpdate() {
      var uri = "/tbStore/add";
      if (this.title == "门店更新") {
        uri = "/tbStore/update";
      }
      var _this = this;
      this.$http
        .post(uri, this.form)
        .then(function (response) {
          console.log(response);
          if (response.data.code == 200) {
            _this.$message({
              message: "操作成功",
              type: "success",
            });
            _this.dialogFormVisible = false;
            _this.loadData();
          } else {
            _this.$message("操作失败");
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    //处理文件成功后的处理方法
    handleFileSuccess(res, file) {
      // alert(JSON.stringify(file))
      // alert(JSON.stringify(file.response.data.filePath))
      //回显上传图片
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.storeimage = file.response.data.filePath;
    },
    //处理文件成功前的处理方法
    beforeFileUpload(file) {
      const FILE_NAME = file.name;
      if (
        FILE_NAME.substring(FILE_NAME.lastIndexOf(".")) !== ".bmp" &&
        FILE_NAME.substring(FILE_NAME.lastIndexOf(".")) !== ".jpg" &&
        FILE_NAME.substring(FILE_NAME.lastIndexOf(".")) !== ".png"
      ) {
        this.$message.warning("仅支持.bmp.jpg.png文件");
        return false;
      }
      // const isJPG = file.type === 'image/jpeg';
      const isLt6M = file.size / 1024 / 1024 < 6;
      // if (!isJPG) {
      //     this.$message.error('上传头像图片只能是 JPG 格式!');
      // }
      if (isLt6M) {
        this.file = file;
        return true;
      }
      this.$message.warning("请上传不超过6M的文件.");
      return false;
    },
  },
  //声明注解
  components: {},
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
#allmap {
  height: 450px;
  width: 100%;
  margin: 10px 0;
}
</style>
